using System;
using System.Collections.Generic;
using System.Configuration;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace Storage
{
    public class MongoDbStorageProxy : IStorageProxy
    {
        private readonly MongoDatabase database;
        private readonly MongoCollection<Entity> files;

        public MongoDbStorageProxy()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ImageConnectionString"].ConnectionString;
            string dbName = ConfigurationManager.AppSettings["BaseName"];

            database = MongoServer.Create(connectionString).GetDatabase(dbName);
            files = database.GetCollection<Entity>("files");
        }

        public void Save(Entity entity)
        {
            files.Save(entity);
        }

        public Entity Read(Guid id)
        {
            var query = new QueryDocument("_id", id);
            var result = files.FindOne(query);
            if (result == null)
                throw new EntityNotFoundException();
            return result;
        }

        public Guid[] EnumerateAll()
        {
            var result = new List<Guid>();
            FieldsBuilder includeFields = Fields.Include(new[] { "_id" });
            foreach (var entity in files.FindAll().SetFields(includeFields))
                result.Add(entity.Id);
            return result.ToArray();
        }
    }
}